<template>
  <a-modal class="common-modal" :title="title" :footer="null" :width="modalWidth" :visible="visible" :confirm-loading="confirmLoading" @cancel="handleCancel" :maskClosable="false" style="top:5%;">
    <a-spin :spinning="confirmLoading"> 
      <a-form :model="formState" @validateFields="handleOk" ref="formRef" :layout="props.layouts" class="common-modal-content"> 
        <a-row>
          <a-col :span="item.cloSapn || cloSapn" v-for="(item,index) in formItems" :key="index">
            <a-form-item :labelCol="item.labelCol || labelCol" :wrapperCol="item.wrapperCol || wrapperCol" :label="$t(item.label)" :rules="item.rules" :name="item.column">
              <a-input :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" autoComplete="off" v-model:value.trim="formState[item.column]" v-if="item.type == 'input'" :disabled="item.disabled" allowClear :maxLength="item.maxLength || 999999" />

              <a-input-number :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-model:value="formState[item.column]" v-if="item.type == 'inputNumber'" :disabled="item.disabled" :min="item.minNo || 0" />

              <a-textarea :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-model:value.trim="formState[item.column]" v-if="item.type == 'textarea'" :disabled="item.disabled" />

              <a-select v-model:value="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'select'" :disabled="item.disabled" allowClear>
                <a-select-option v-for="(el,i) in (item.optionsList|| selectOptions[item.column])" :value="item.isName ? (item.needTrans ? $t(el.name) : el.name): (el.value || el.id)" :key="i" :disabled="el.disabled">
                  {{ item.needTrans ? (item.isName ? $t(el.name) : ($t(el.label) || $t(el.name) ) ): (item.isName ?  el.name : el.label || el.name )}}
                </a-select-option>
              </a-select>

              <a-select v-model:value="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'multiSelect'" :disabled="item.disabled" allowClear mode="multiple">
                <a-select-option v-for="(el,i) in (item.optionsList|| selectOptions[item.column])" :value="el.value || el.id" :key="i">
                  {{ item.needTrans ?  $t(el.label || el.name) : (el.label || el.name )}}
                </a-select-option>
              </a-select>

              <a-tree-select v-model:value="formState[item.column]" show-search style="width: 100%" :dropdown-style="{ maxHeight: '500px', overflow: 'auto' }" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'selectTree'" :disabled="item.disabled" allowClear tree-default-expand-all :tree-data="item.optionsList|| selectOptions[item.column]" :field-names="item.fieldNames || fieldNames"></a-tree-select>

              <a-date-picker v-model:value="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'date'" :disabled="item.disabled">
              </a-date-picker>

              <a-date-picker v-model:value="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" showTime format="YYYY-MM-DD HH:mm:ss" v-if="item.type == 'dateTime'" :disabled="item.disabled">
              </a-date-picker>

              <a-radio-group v-model:value="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'radio'" :disabled="item.disabled ">
                <a-radio v-for="(el,i) in (item.optionsList || selectOptions[item.column])" :value="el.value" :key="i">{{$t(el.label)}}</a-radio>
              </a-radio-group>

              <a-switch v-model:checked="formState[item.column]" :placeholder="item.placeholder ? $t(item.placeholder): item.placeholder" v-if="item.type == 'switch'" :disabled="item.disabled" />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="common-modal-footer">
        <a-button @click="handleCancel" class="cancel">{{$t('common.cancel')}}</a-button>
        <a-button @click="handleOk" type="primary" class="confirm">{{$t('common.ok')}}</a-button>
      </div>
    </a-spin>
  </a-modal>
</template>

<script setup name="commonModal">
import { nextTick, ref } from 'vue'
import axios from '@/utils/request'
import { cloneDeep } from 'lodash'
// import moment from 'moment'
import modalData from './modalData'
import i18n from '@/locales/index' 
const { t } = i18n.global
const props = defineProps({
  tableName: {
    type: String,
    required: true,
  },
  modalWidth: {
    type: Number,
    dafault: 500,
  },
  cloSapn: {
    type: Number,
    dafault: 12,
  },
  modalTitle: {
    type: String,
  },
  externalOperation: {
    type: Boolean,
    default: false,
  },
  isUrlSave: {
    type: Boolean,
    default: false,
  },
  needChangeTitle: {
    type: Boolean,
    default: true,
  },
  isProdTime: {
    type: Boolean,
    default: false,
  },
  layouts: {
    type: String,
    default: 'vertical'
  },
  
})
const emits = defineEmits(['handleOk', 'ok'])
const fieldNames = { children: 'children', label: 'label', value: 'id' }
const labelCol = {
  xs: { span: 23 },
  sm: { span: 23 },
}
const wrapperCol = {
  xs: { span: 23 },
  sm: { span: 23 },
}
let title = ref('')
let visible = ref(false)
let isEdit = ref(false)
let confirmLoading = ref(false)
const selectOptions = ref({})
const url = modalData.url[props.tableName]
const formItems = ref(modalData.modelItem[props.tableName]) 
let recordInfo = ref({})
let formState = ref({})
const formRef = ref()
const add = () => {
  edit({})
}
// const handleChange = (value, column) => {
//   console.log('value', value);
//   formState.value[column] = value ? `${value}`.replace(/^(0+)|[^\d]+/g, '') : ''
// }
const edit = async (record, editable = false) => {
  title.value = props.needChangeTitle
    ? `${editable ? t('common.edit') : t('common.addNew')} ${props.modalTitle}`
    : props.modalTitle
  // initFormItems()
  recordInfo.value = Object.assign({}, record)
  visible.value = true
  isEdit.value = editable
  await nextTick()
  formState.value = cloneDeep(record)
  formRef.value.resetFields()
}
// const initFormItems = () => {
//   let list = [...formItems.value]
//   list.forEach(i=> {
//     Array.isArray(i.rules) && i.rules.forEach(el=> {
//       el.message = el.message18 ? t(el.message18) : null
//     }) 
//   }) 
//   formItems.value = list
// }
const handleOk = async () => {
  const sendUrl = props.isUrlSave ? url.save : recordInfo.value.id ? url.edit : url.add
  try {
    const values = await formRef.value.validateFields()
    confirmLoading.value = true
    if (props.externalOperation) {
      emits('handleOk')
    } else {
      let params = {
        id: props.isProdTime ? null : recordInfo.value.id,
        stationId: props.isProdTime ? recordInfo.value.stationId : null,
        ...values,
      }
      const res = await axios.postAction(sendUrl, params)
      confirmLoading.value = false
      if (res.success) {
        emits('ok', params)
        visible.value = false
      }
    }
  } catch (err) {
    console.log('0000000', err)
  }

  confirmLoading.value = false
}
const handleCancel = () => {
  visible.value = false
  confirmLoading.value = false
  formState.value = {}
  formRef.value.resetFields()
}

const initSelectOptions = (obj) => {
  selectOptions.value = obj
}

defineExpose({
  add,
  edit,
  initSelectOptions,
})
</script>
